package com.qf.dynamicdatasource;

import com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import javax.swing.*;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class DataSourceConfig {

    @Value("${spring.datasource1.username}")
    private String username;

    @Value("${spring.datasource1.password}")
    private String password;

    @Value("${spring.datasource1.driver-class-name}")
    private String driverClass;

    @Value("${spring.datasource1.url}")
    private String url1;

    @Value("${spring.datasource2.url}")
    private String url2;

    @Value("${spring.datasource1.alias}")
    private String db1;

    @Value("${spring.datasource2.alias}")
    private String db2;

    @Bean
    public HikariDataSource dataSource1(){
        HikariDataSource dataSource = new HikariDataSource();
        dataSource.setDriverClassName(driverClass);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        dataSource.setJdbcUrl(url1);
        return dataSource;
    }

    @Bean
    public HikariDataSource dataSource2(){
        HikariDataSource dataSource = new HikariDataSource();
        dataSource.setDriverClassName(driverClass);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        dataSource.setJdbcUrl(url2);
        return dataSource;
    }

    @Bean
    public MyRoutingDataSource myRoutingDataSource(DataSource dataSource1,DataSource dataSource2){

        // 1.把两个数据源封装到Map中
        Map<Object,Object> map = new HashMap<>();
        map.put(db1,dataSource1);
        map.put(db2,dataSource2);


        // 2.把Map放入到路由的数据源
        MyRoutingDataSource myRoutingDataSource = new MyRoutingDataSource();
        myRoutingDataSource.setTargetDataSources(map);
        myRoutingDataSource.setDefaultTargetDataSource(dataSource1);

        return  myRoutingDataSource;
    }


    @Bean
    public MybatisSqlSessionFactoryBean sqlSessionFactoryBean(DataSource myRoutingDataSource){
        MybatisSqlSessionFactoryBean mybatisSqlSessionFactoryBean = new MybatisSqlSessionFactoryBean();
        mybatisSqlSessionFactoryBean.setDataSource(myRoutingDataSource);
        return  mybatisSqlSessionFactoryBean;
    }



}
